package com.niit.gams.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.niit.gams.dao.SysRoleMapper;
import com.niit.gams.pojo.SysRole;
import com.niit.gams.service.SysRoleService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysRoleServiceImpl implements SysRoleService {
  private SysRoleMapper sysRoleMapper;

  public SysRoleServiceImpl(SysRoleMapper sysRoleMapper) {
    this.sysRoleMapper = sysRoleMapper;
  }

  @Override
  public List<SysRole> findRolesByUserId(long uid) {
    return sysRoleMapper.findRolesByUserId(uid);
  }

  @Override
  public PageInfo<SysRole> findUsersByPage(Integer curPage, Integer pageSize) {
    PageHelper.startPage(curPage, pageSize);
    List<SysRole> roleList = sysRoleMapper.findUsersByPage(curPage, pageSize);
     PageInfo<SysRole> pageInfo = new PageInfo<>(roleList);
     return pageInfo;
  }

  @Override
  public boolean addRole(SysRole role) {
    boolean flag = sysRoleMapper.insert(role)>0;
    return flag;
  }

  @Override
  public boolean delRole(Integer rid) {
    boolean flag = sysRoleMapper.deleteByPrimaryKey(rid)>0;
    return flag;
  }

  @Override
  public List<SysRole> findRoles() {
    return sysRoleMapper.selectAll();
  }

  @Override
  public List<Long> findRids(long uid) {
    List<SysRole> roles = findRolesByUserId(uid);
    List<Long> rids = new ArrayList<>();
    for (SysRole role:roles) {
      rids.add(role.getId());
    }
    return rids;
  }

  @Override
  public boolean updateUserRoles(Long uid, List<Long> rids) {
    //先删除id用户的所有关联角色
    boolean flag = sysRoleMapper.deleteRidsByUid(uid)>0;
    //重新添加id用户的关联角色
    boolean rFlag  = sysRoleMapper.insertRidsByUid(uid,rids)>0;

    return rFlag;
  }

}
